<?php

namespace app\common\model\banxi\student;

use app\common\enums\AppointmentStatusEnum;
use app\common\enums\CoreCourseTypeEnum;
use app\common\enums\CourseDeliveryTypeEnum;
use app\common\enums\CourseFullTypeEnum;
use app\common\enums\StudentAppointmentStatusEnum;
use app\common\enums\StudentExperienceAppointmentOrderStatusEnum;
use app\common\enums\StudentExperiencePayTypeStatusEnum;
use app\common\model\banxi\core\CoreCourseAppointment;
use app\common\model\banxi\organization\Organization;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\trainer\Trainer;
use app\common\model\common\BaseModel;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 学生体验预约
 */
class StudentExperienceAppointment extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_student_experience_appointment';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'orderStatusCn',
        'payTypeCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'courseId' => 'string',
        'studentId' => 'string',
        'trainerId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getOrderStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['orderStatus'] ?? '');
        return (new StudentExperienceAppointmentOrderStatusEnum())->getDescription($value) ?? '';
    }

    public function getPayTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['payType'] ?? '');
        return (new StudentExperiencePayTypeStatusEnum())->getDescription($value) ?? '';
    }


    //-----------------------------------------------------------------------------------
    //｜                                  处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->with([
            'trainerInfo' => function ($query) {
                $query->field('id,name');
            }])->order(['id' => 'desc'])->where($where)->paginate(['page' => $page, 'list_rows' => $limit]);
    }

    /*
     * 抢单
     * @param $orderId 体验单id
     * @param $trainerId 教练id
     * @return true
     * */
    public function catchOrder(int $orderId, int $trainerId)
    {
        Db::startTrans();
        try {
            $appointmentInfo = self::where(['id'=>$orderId])->find();
            if (!$appointmentInfo) {
                throw new ValidateException('订单不存在');
            }
            if ($appointmentInfo['orderStatus'] != StudentExperienceAppointmentOrderStatusEnum::PAID) {
                throw new ValidateException('订单状态有误');
            }

            //创建排课预约
            $data = [
                'trainerId'=>$trainerId,
                'studentId'=>$appointmentInfo['studentId'],
                'studentOrganizationId'=>$appointmentInfo['studentOrganizationId'],
                'date'=>$appointmentInfo['date'],
                'startTime'=>$appointmentInfo['startTime'],
                'endTime'=>$appointmentInfo['endTime'],
                'courseType'=>$appointmentInfo['courseType'],
                'courseId'=>$appointmentInfo['courseId'],
                'courseName'=>$appointmentInfo['courseName'],
                'courseFullType'=>$appointmentInfo['courseFullType'],
                'courseDeliveryType'=>$appointmentInfo['courseDeliveryType']
//                'isStudentAppointment'=>1
            ];
            $CoreCourseAppointmentModel = new CoreCourseAppointment();
            $CourseAppointment = $CoreCourseAppointmentModel->create($data);
//            $appointmentInfo->save(['appointmentStatus'=>StudentAppointmentStatusEnum::E2]);
            // 使用 compare and swap 方式更新订单状态，防止并发问题
            $result = self::where('id', $orderId)
                ->where('orderStatus', StudentExperienceAppointmentOrderStatusEnum::PAID)
                ->where('trainerId', 0)
                ->update([
                    'orderStatus' => StudentExperienceAppointmentOrderStatusEnum::RECEIVED,
                    'trainerId' => $trainerId,
                    'courseAppointmentId' => $CourseAppointment->id,
                ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());
        }
        return true;
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


    public function trainerInfo()
    {
        return $this->hasOne(Trainer::class, 'id', 'trainerId');
    }

    public function studentInfo()
    {
        return $this->hasOne(Student::class, 'id', 'studentId');
    }
}